﻿using System;
using System.Collections.Generic;
using System.Text;

namespace System.Data.SugarClient.Soap.V1
{

	internal class V1GetAvailableModulesAction : V1SessionAction
	{

		private static IDictionary<int, V1GetAvailableModulesActionResult> _cache = new Dictionary<int, V1GetAvailableModulesActionResult>(10);

		#region Constructors

		internal V1GetAvailableModulesAction(
			SugarSoapV1.sugarsoap service,
			string session)
			: base(service, session) 
		{
		}

		#endregion

		protected override V1ActionResult ExecuteInner()
		{
			return FindFromCache() ?? ExecuteSoap();
		}

		protected V1GetAvailableModulesActionResult FindFromCache()
		{
			Trace.Debug("{0}.FindFromCache(),Session:{1}", this.GetType().Name, this.Session);
			int hash = this.Session.GetHashCode();
			return (_cache.ContainsKey(hash)) ? _cache[hash] : null;
		}

		protected V1GetAvailableModulesActionResult ExecuteSoap()
		{
			Trace.Debug("{0}.ExecuteSoap(),Session:{1}", this.GetType().Name, this.Session);
			var soap =
				this.SoapService.get_available_modules(
					this.Session);
			V1GetAvailableModulesActionResult result = new V1GetAvailableModulesActionResult(this, soap);
			if(10 <= _cache.Count) _cache.Clear();
			_cache[this.Session.GetHashCode()] = result;
			return result;
		}
	}

	internal class V1GetAvailableModulesActionResult : V1SessionActionResult, IGetAvailableModulesActionResult
	{

		internal V1GetAvailableModulesActionResult(
			V1GetAvailableModulesAction action,
			SugarSoapV1.module_list result)
			: base(action)
		{
			this._result = result;
			Array.Sort<string>(this.RawResult.modules);
		}

		#region Fields

		private readonly SugarSoapV1.module_list _result;

		#endregion

		internal SugarSoapV1.module_list RawResult
		{
			get { return _result; }
		}

		public string[] AvailableModules
		{
			get { return this.RawResult.modules; }
		}

		public override bool Success
		{
			get
			{
				if (RawResult.error == null) return true;
				else if (RawResult.error.number == null) return true;
				else if ("0".Equals(RawResult.error.number)) return true;
				else return false;
			}
		}

	}

}
